package com.moli.job;

import com.moli.domain.entity.Article;
import com.moli.service.ArticleService;
import com.moli.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author： XC
 * @Date： 2023-06-08 10:55
 * @Description： 更新浏览量时去更新redsi中的数据
 */

@Component
public class UpdateViewCountJob {

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private ArticleService articleService;

	@Scheduled(cron = "0/55 * * * * ?")
	public void updateViewCount(){
		//获取redis中的浏览量
		Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");

		List<Article> articles = viewCountMap.entrySet()
				.stream()
				.map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
				.collect(Collectors.toList());
		//更新到数据库中
		articleService.updateBatchById(articles);

	}
}